package com.loveofsoftware.quotes;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;
import android.widget.Toast;

public class QuotePageActivity extends Activity {

	PowerManager.WakeLock wl = null;

	@Override
	protected void onPause() {
		super.onPause();
		if (null != wl && wl.isHeld()) {
			wl.release();
			System.out.println("Released the wake lock");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

		if (null == wl)
			wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Bliss");
		if (!wl.isHeld()) {
			wl.acquire();
			System.out.println("Aquired the wake lock");
		}
	}

	String[] quotes;
	String[] authors;
	int currIndex = 0;
	TextView textview = null;

	private static final int MODE_SHOW_UNSEEN = 1;
	private static final int MODE_SHOW_SEEN = 2;
	private static final int MODE_SHOW_FAVORITES= 3;
	
	int mMode = MODE_SHOW_UNSEEN ;	

	private static final String PREFS_NAME = "com.loveofsoftware.quotes";
	ArrayList<String> seenQuotesArrayList = new ArrayList<String>();
	ArrayList<String> favoriteQuotesArrayList = new ArrayList<String>();

	public QuotePageAdvancedGestureDetector advDetector = new QuotePageAdvancedGestureDetector();
	public GestureDetector detector = null;

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("CURRINDEX", currIndex);
		outState.putInt("MODE", mMode);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		String seenQuotes = settings.getString("seenQuotes", null);
		System.out.println("Retrieved saved quotes : " + seenQuotes);
		if (null != seenQuotes && seenQuotes.length() > 0) {
			String[] seenQuotesArray = seenQuotes.split(":");
			for (int i = 0; i < seenQuotesArray.length; i++) {
				seenQuotesArray[i] = seenQuotesArray[i].trim();
				if (seenQuotesArray[i].length() > 0)
					seenQuotesArrayList.add(seenQuotesArray[i]);
			}
		}

		String favoriteQuotes = settings.getString("favoriteQuotes", null);
		if (null != favoriteQuotes && favoriteQuotes.length() > 0) {
			String[] favoriteQuotesArray = favoriteQuotes.split(":");
			for (int i = 0; i < favoriteQuotesArray.length; i++) {
				favoriteQuotesArray[i] = favoriteQuotesArray[i].trim();
				if (favoriteQuotesArray[i].length() > 0)
					favoriteQuotesArrayList.add(favoriteQuotesArray[i]);
			}
		}

		if (null != savedInstanceState
				&& 0 != savedInstanceState.getInt("TOKEN")) {
			currIndex = savedInstanceState.getInt("CURRINDEX");
			mMode = savedInstanceState.getInt("MODE");
		} else {
			Resources r = getResources();
			quotes = r.getStringArray(R.array.quotesArray);
			authors = r.getStringArray(R.array.authorsArray);
			if (quotes.length != authors.length) {
				System.out
						.println("ERROR ============= quotes and authors do not match "
								+ quotes.length + "," + authors.length);
			}
			currIndex = (new Date()).getDay() % quotes.length;
		}

		if (currIndex >= quotes.length)
			currIndex = 0;

		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT);
		textview = new TextView(this);
		textview.setLayoutParams(lp);
		textview.setTextColor(Color.YELLOW);
		textview.setTextSize(16);// 16sp
		textview.setSingleLine(false);

		textview.setGravity(Gravity.CENTER);

		textview.setText("");
		setContentView(textview);

		showQuote(null, false);

		detector = new GestureDetector(this, advDetector);

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// System.out.println("BALA *****************  Event : "+event);
		detector.onTouchEvent(event);
		return true;
	}

	Iterator<String> favIterator = null;
	Iterator<String> seenIterator = null;

	public void showQuote(MotionEvent event, boolean moveFirst) {
		boolean bSavePref = false;
		if (moveFirst)
			currIndex++;
		if (mMode == MODE_SHOW_FAVORITES) {
			if (null == favIterator)
				favIterator = favoriteQuotesArrayList.iterator();
			if (favIterator.hasNext()) {
				favIterator = favoriteQuotesArrayList.iterator();
			}
			if (favIterator.hasNext()) {
				try {
					currIndex = Integer.parseInt(favIterator.next());
				} catch (NumberFormatException e) {
					return;
				}
				if (null == event)
					setText(0, 0);
				else
					setText(event.getX(), event.getY());
			}
			return;
		}else if (mMode == MODE_SHOW_SEEN) {
			if (null == seenIterator)
				seenIterator = seenQuotesArrayList.iterator();
			if (!seenIterator.hasNext()) {//Reset
				seenIterator = seenQuotesArrayList.iterator();
			}
			if (seenIterator.hasNext()) {
				try {
					currIndex = Integer.parseInt(seenIterator.next());
				} catch (NumberFormatException e) {
					return;
				}
				if (null == event)
					setText(0, 0);
				else
					setText(event.getX(), event.getY());
			}
			return;
		}

		for (int i = 0; i < quotes.length; i++) {

			currIndex = currIndex % quotes.length;
			if (!seenQuotesArrayList.contains("" + currIndex)) {
				seenQuotesArrayList.add("" + currIndex);
				bSavePref = true;
				break;
			}
			currIndex++;
		}
		currIndex = currIndex % quotes.length;
		if (null == event)
			setText(0, 0);
		else
			setText(event.getX(), event.getY());
		if (bSavePref) {
			String buf = "";
			Iterator<String> iter = seenQuotesArrayList.iterator();
			while (iter.hasNext())
				buf += ":" + iter.next();
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("seenQuotes", buf);
			editor.commit();
			System.out.println("Saved: " + buf);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;

	}

	private void setText(float x, float y) {
		AlphaAnimation animation = new AlphaAnimation(0, 100);
		animation.setDuration(30000);
		textview.setAnimation(animation);
		String s = quotes[currIndex] + "\n\n" + authors[currIndex];
		final int characters = s.length();
		if (characters < 80) {
			textview.setTextSize(32);
		} else {
			textview.setTextSize(16);// 16sp
		}

		textview.setText(s);
		// ScaleAnimation sAnimation = new ScaleAnimation(0.5f, 1.5f, 0.5f,
		// 1.5f, x, y);
		// sAnimation.setDuration(10000);
		// textview.setAnimation(sAnimation);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.next:
			currIndex = (currIndex + 1) % quotes.length;
			setText(0, 0);
			return true;
		case R.id.prev:
			if (0 == currIndex)
				currIndex = quotes.length - 1;
			else
				currIndex--;
			setText(0, 0);
			return true;
		case R.id.favourite:
			if (!favoriteQuotesArrayList.contains("" + currIndex)) {
				favoriteQuotesArrayList.add("" + currIndex);
				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				SharedPreferences.Editor editor = settings.edit();
				String buf = "";
				Iterator<String> iter = favoriteQuotesArrayList.iterator();
				while (iter.hasNext())
					buf += ":" + iter.next();
				editor.putString("favoriteQuotes", buf);
				editor.commit();
				Toast.makeText(this, "Saved to favorites", Toast.LENGTH_LONG)
						.show();
			}
			return true;
		case R.id.show_favourite:
			mMode = MODE_SHOW_FAVORITES;
			return true;
		case R.id.show_seen:
			mMode = MODE_SHOW_SEEN;
			return true;
		case R.id.exit:
			this.finish();
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	public class QuotePageAdvancedGestureDetector extends
			SimpleOnGestureListener {

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			return super.onDoubleTap(e);
		}

		@Override
		public boolean onDoubleTapEvent(MotionEvent e) {
			return super.onDoubleTapEvent(e);
		}

		@Override
		public void onLongPress(MotionEvent e) {
			textview.setTextSize(textview.getTextSize() + 4);
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			textview.scrollBy((int) distanceX, (int) distanceY);
			return true;
		}

		@Override
		public void onShowPress(MotionEvent e) {

		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			System.out.println("Single tap up");
			return true;
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			System.out.println("Single tap confirmed");
			showQuote(e, true);
			return true;
		}

		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			showQuote(e1, true);
			return true;
		}

	}
}